//
//  HomeUploadFileTableViewCell.m
//  ZJControlsClass
//
//  Created by wandoufo on 2024/12/18.
//

#import "HomeUploadFileTableViewCell.h"
#import "SaTMNewWatermarkPhotoVc.h"
#import "HomeSeeFileWebViewViewController.h"


@interface HomeUploadFileTableViewCell ()<UIDocumentInteractionControllerDelegate>

@property (nonatomic,strong) UIView * v;
@property (nonatomic,strong) UIDocumentInteractionController *documentController;
@property (nonatomic,strong) NSMutableArray *array;

@end


@implementation HomeUploadFileTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        
        [self configUI];
        
        
        
    }
    return self;
}


-(void)configUI{
    
    [self.contentView addSubview:self.requiredLabel];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.inputTextF];
    [self.contentView addSubview:self.rightImg];
    [self.contentView addSubview:self.fileBtn];
    [self.contentView addSubview:self.v];

    
    [self.requiredLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView.mas_top);
        make.left.equalTo(self.contentView).with.offset(ALIGN_WIDTH_PT(15));
        make.size.equalTo(@(CGSizeMake(10, 50)));
    }];
    
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView.mas_top);
        make.left.equalTo(self.requiredLabel.mas_right);
        make.height.equalTo(@(ALIGN_HEIGHT_PT(50)));
        make.width.equalTo(@(SCREEN_WIDTH / 2 - ALIGN_WIDTH_PT(15)));
    }];
    
    [self.inputTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.titleLabel.mas_centerY);
        make.left.equalTo(self.titleLabel.mas_right);
        make.right.equalTo(self.contentView).with.offset(-ALIGN_WIDTH_PT(30));
        make.width.equalTo(@(SCREEN_WIDTH - ALIGN_WIDTH_PT(30) / 2));
        make.height.equalTo(@(ALIGN_HEIGHT_PT(50)));
    }];
    
    [self.rightImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.titleLabel.mas_centerY);
        make.right.equalTo(self.contentView).with.offset(-ALIGN_WIDTH_PT(10));
        make.width.equalTo(@(ALIGN_WIDTH_PT(6)));
        make.height.equalTo(@(ALIGN_WIDTH_PT(10)));
    }];
    
    [self.fileBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).with.offset(ALIGN_WIDTH_PT(15));
        make.right.equalTo(self.contentView).with.offset(-ALIGN_WIDTH_PT(15));
        make.top.equalTo(self.titleLabel.mas_bottom);
        make.height.equalTo(@(ALIGN_HEIGHT_PT(49)));
    }];
    
    [self.v mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).with.offset(ALIGN_WIDTH_PT(15));
        make.right.equalTo(self.contentView).with.offset(-ALIGN_WIDTH_PT(15));
        make.bottom.equalTo(self.contentView.mas_bottom).with.offset(-ALIGN_HEIGHT_PT(0.5));
        make.height.equalTo(@(ALIGN_HEIGHT_PT(0.5)));
    }];
    
}

-(void)setParamer:(NSMutableDictionary *)paramer{
    _paramer = paramer;
    self.titleLabel.text = paramer[@"title"];
    
    self.array = @[].mutableCopy;
    
    // 判断是否已经解析过
    if ([paramer[@"temp"] isKindOfClass:[NSArray class]]) {
        self.array = paramer[@"temp"];
    } else {
        NSData *jsonData = [paramer[@"temp"] dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
        self.array = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        
        NSLog(@"=====-----444444%@",self.array);
        if (error) {
            NSLog(@"JSON解析出错：%@", error);
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"JSON解析formItems出错：%@", error] buttonAction:^{
                
            }];
            return;
        }
    }
    
    if (self.array.count != 0) {
        [self.fileBtn setTitle:[self.array firstObject][@"name"] forState:(UIControlStateNormal)];
    }
    
    self.rightImg.hidden = YES;
    
}


-(void)setModel:(HomeUnitModel *)model{
    _model = model;
    
    if ([model.props.required boolValue] == YES) {
        self.requiredLabel.hidden = NO;
    }else{
        self.requiredLabel.hidden = YES;
    }
    
    self.inputTextF.placeholder = model.props.placeholder;
    self.titleLabel.text = model.props.title;
    [self.fileBtn setTitle:model.props.url forState:(UIControlStateNormal)];
    
}


-(void)responsTo_fileBtn{
    if(self.paramer){
        
        if ([[self.array firstObject][@"url"] length] != 0){
            // 检查是否是本地文件路径
            NSString *filePath = [self.array firstObject][@"url"];
            NSURL *fileURL;
            
            if ([filePath hasPrefix:@"http://"] || [filePath hasPrefix:@"https://"]) {
                fileURL = [NSURL URLWithString:filePath];
            } else {
                fileURL = [NSURL fileURLWithPath:filePath];
            }
            
//
            
            
            // 检查文件是否存在
//            if (![fileURL checkResourceIsReachableAndReturnError:nil]) {
//                [LUtilityTools showAlertWithTitle:@"温馨提示" message:@"文件不存在或无法访问" buttonAction:^{
//                    
//                }];
//                return;
//            }
            
            HomeSeeFileWebViewViewController * vc = [HomeSeeFileWebViewViewController new];
            vc.fileUrl = filePath;
            [[SaViewControllerUtils currentViewController].navigationController pushViewController:vc animated:YES];
            
            
            
            
//            // 创建文档交互控制器
//            self.documentController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
//            self.documentController.delegate = self;
//            
//            // 获取当前视图控制器
//            UIViewController *currentVC = [SaViewControllerUtils currentViewController];
//            if (currentVC) {
//                @try {
//                    // 直接打开预览
//                    BOOL presented = [self.documentController presentPreviewAnimated:YES];
//                    if (!presented) {
//                        // 如果预览失败，则显示打开方式选项
//                        [self.documentController presentOptionsMenuFromRect:self.fileBtn.frame
//                                                                  inView:self.contentView
//                                                                animated:YES];
//                    }
//                } @catch (NSException *exception) {
//                    NSLog(@"打开文件异常: %@", exception);
//                    [LUtilityTools showAlertWithTitle:@"温馨提示" message:@"打开文件失败,请确认文件格式正确" buttonAction:^{
//                        
//                    }];
//                }
//            }
        }
        
        
        
    }else{
        if (self.model.props.url.length != 0){
            // 检查是否是本地文件路径
            NSString *filePath = self.model.props.url;
            NSURL *fileURL;
            
            if ([filePath hasPrefix:@"http://"] || [filePath hasPrefix:@"https://"]) {
                fileURL = [NSURL URLWithString:filePath];
            } else {
                fileURL = [NSURL fileURLWithPath:filePath];
            }
            
//            // 检查URL是否有效
//            if (!fileURL) {
//                NSLog(@"无效的文件URL");
//                return;
//            }
            
//            // 创建文档交互控制器
//            self.documentController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
//            self.documentController.delegate = self;
//            
//            // 获取当前视图控制器
//            UIViewController *currentVC = [SaViewControllerUtils currentViewController];
//            if (currentVC) {
//                // 直接打开预览
//                BOOL presented = [self.documentController presentPreviewAnimated:YES];
//                if (!presented) {
//                    // 如果预览失败，则显示打开方式选项
//                    [self.documentController presentOptionsMenuFromRect:self.fileBtn.frame
//                                                              inView:self.contentView
//                                                            animated:YES];
//                }
//            }
            HomeSeeFileWebViewViewController * vc = [HomeSeeFileWebViewViewController new];
            vc.fileUrl = filePath;
            [[SaViewControllerUtils currentViewController].navigationController pushViewController:vc animated:YES];
            
        }
    }
    
}

// 添加必要的 UIDocumentInteractionControllerDelegate 方法
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
    return [SaViewControllerUtils currentViewController];
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.contentView;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller {
    return self.contentView.frame;
}

#pragma mark -- 懒加载

-(UILabel *)requiredLabel{
    if (!_requiredLabel) {
        _requiredLabel = [UILabel new];
        _requiredLabel.text = @"*";
        _requiredLabel.textColor = [UIColor redColor];
        _requiredLabel.font = FONT14;
        _requiredLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _requiredLabel;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.text = @"申办单位全称";
        _titleLabel.font = FONT14;
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
    }
    return _titleLabel;
}

-(UITextField *)inputTextF{
    if (!_inputTextF) {
        _inputTextF = [UITextField new];
        _inputTextF.textColor = [UIColor blackColor];
        _inputTextF.font = FONT14;
        _inputTextF.textAlignment = NSTextAlignmentLeft;
        _inputTextF.enabled = NO;
    }
    return _inputTextF;
}

-(UIImageView *)rightImg{
    if (!_rightImg) {
        _rightImg = [UIImageView new];
        _rightImg.image = [UIImage imageNamed:@"Vector"];
    }
    return _rightImg;
}
-(UIView *)v{
    if (!_v) {
        _v = [UIView new];
        _v.backgroundColor = COLOR_RGB(215, 216, 217);
    }
    return _v;
}

-(UIButton *)fileBtn{
    if (!_fileBtn) {
        _fileBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_fileBtn setTitleColor:COLOR_RGB(50, 113, 237) forState:(UIControlStateNormal)];
        _fileBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_fileBtn addTarget:self action:@selector(responsTo_fileBtn) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _fileBtn;
}


@end
